package com.ym.medical.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.thread.GlobalThreadPool;
import com.alibaba.fastjson.JSONObject;
import com.ym.base.enums.FlagEnum;
import com.ym.common.constant.DictEnum;
import com.ym.common.enums.UserUserTypeEnum;
import com.ym.core.utils.JPushUtil;
import com.ym.core.utils.tkmybatis.BaseSVImpl;
import com.ym.core.utils.tkmybatis.TK;
import com.ym.medical.dao.JpushAccountDao;
import com.ym.medical.domain.bo.PushBean;
import com.ym.medical.domain.bo.PushBeanExtraVo;
import com.ym.medical.domain.entity.DoctorDetailsEntity;
import com.ym.medical.domain.entity.DoctorStudioEntity;
import com.ym.medical.domain.entity.InformationEntity;
import com.ym.medical.domain.entity.InquiryOrderEntity;
import com.ym.medical.domain.entity.JpushAccountEntity;
import com.ym.medical.domain.entity.OrderFlowRecordEntity;
import com.ym.medical.domain.entity.PatientDetailEntity;
import com.ym.medical.domain.entity.StudioPersonnelEntity;
import com.ym.medical.domain.entity.UserEntity;
import com.ym.medical.enums.DoctorStudioStatusEnum;
import com.ym.medical.enums.InformationInforStateEnum;
import com.ym.medical.enums.InformationInforTypeEnum;
import com.ym.medical.enums.InquiryOrderIoTypeEnum;
import com.ym.medical.enums.OrderFlowRecordTypeEnum;
import com.ym.medical.enums.UserCertStateEnum;
import com.ym.medical.service.IDoctorDetailsSV;
import com.ym.medical.service.IDoctorStudioSV;
import com.ym.medical.service.IInformationSV;
import com.ym.medical.service.IInquiryOrderSV;
import com.ym.medical.service.IJpushAccountSV;
import com.ym.medical.service.IOrderFlowRecordSV;
import com.ym.medical.service.IPatientDetailSV;
import com.ym.medical.service.IStudioPersonnelSV;
import com.ym.medical.service.IUserSV;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 极光账号Service业务层处理
 *
 * @author ym
 * @date 2020-08-21
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class JpushAccountSVImpl extends BaseSVImpl<JpushAccountEntity, JpushAccountDao> implements IJpushAccountSV {

	@Autowired
	private IOrderFlowRecordSV orderFlowRecordSV;

	@Autowired
	private IInquiryOrderSV inquiryOrderSV;

	@Autowired
	private IDoctorDetailsSV doctorDetailsSV;

	@Autowired
	private IStudioPersonnelSV studioPersonnelSV;

	@Autowired
	private IInformationSV informationSV;

	@Autowired
	private IUserSV userSV;

	@Autowired
	private IPatientDetailSV patientDetailSV;

	@Autowired
	private IDoctorStudioSV doctorStudioSV;

	@Override
	public void pushMessage(PushBean pushBean, boolean persistence) {
		//插入消息表持久化
		InformationEntity information = new InformationEntity();
		PushBeanExtraVo extrasBean = pushBean.getExtrasBean();
		String msg = JPushUtil.getMessageByPushBean(pushBean);
		extrasBean.setContent(msg);
		if ("02".equals(extrasBean.getMsgTypeParent())) {
			//工作室消息
			information.setInforType(InformationInforTypeEnum.STUDIO_NEWS.getKey());
		} else if ("01".equals(extrasBean.getMsgTypeParent())) {
			//系统消息
			information.setInforType(InformationInforTypeEnum.SYSTEM.getKey());
		} else if ("03".equals(extrasBean.getMsgTypeParent())) {
			//系统消息
			information.setInforType(InformationInforTypeEnum.INQUIRY.getKey());
		}
		information.setSendTime(new Date());
		if (extrasBean.getWhoPush() != null) {
			information.setSendObjId(extrasBean.getWhoPush().getId());
		}
		if (extrasBean.getPushWho() != null) {
			information.setReceiverObjId(extrasBean.getPushWho().getId());
		}
		information.setInforTitle(pushBean.getAlert());
		information.setInforData(extrasBean.getContent());
		information.setExtContent(JSONObject.toJSONString(extrasBean));
		information.setCreateTime(new Date());
		information.setDestination(UserUserTypeEnum.DOCTOR.getKey());
		information.setInforState(InformationInforStateEnum.NO_READ.getKey());
		if (persistence) {
			informationSV.insert(information);
		}
		//推送
		List<JpushAccountEntity> jpushAccounts = mapper.select(JpushAccountEntity.builder().userId(pushBean.getExtrasBean().getPushWho().getId()).build());
		JPushUtil.pushAllAlias(pushBean, jpushAccounts);
	}

	@Override
	public void pushOrderMsg2Doctors(Long orderId) {
		GlobalThreadPool.execute(() -> {
			InquiryOrderEntity inquiryOrder = inquiryOrderSV.selectById(orderId);
			OrderFlowRecordEntity orderFlow = orderFlowRecordSV.findNewByOrderId(orderId);
			// 通用推送单子
			PushBean pushBean = new PushBean();
			pushBean.setAlert(" 来新单子了！快去看看吧！");
			PushBeanExtraVo pushBeanExtra = new PushBeanExtraVo();
			pushBeanExtra.setBusinessId(orderId.toString());
			pushBeanExtra.setContent(null);
			pushBeanExtra.setMsgTypeParent("03");
			pushBeanExtra.setMsgTypeSub("04");
			pushBeanExtra.setTime(DateUtil.now());
			UserEntity user = userSV.selectById(inquiryOrder.getUserId());
			PatientDetailEntity patientDetail = patientDetailSV.selectById(inquiryOrder.getPatientId());
			user.setRealName(patientDetail.getName());
			pushBeanExtra.setWhoPush(user);
			// 如果没有指定医生，且为全科
			if (orderFlow == null || orderFlow.getType().equals(OrderFlowRecordTypeEnum.GENERAL.getKey())) {
				List<DoctorDetailsEntity> doctorDetails = doctorDetailsSV.selectList(TK.select(DoctorDetailsEntity.class).column("doct_id").where()
						.andEqualTo(DoctorDetailsEntity::getDoctCategory, OrderFlowRecordTypeEnum.GENERAL.getKey())
						.andEqualTo(DoctorDetailsEntity::getQualificationStatus, UserCertStateEnum.CERTIFIED.getKey())
						.end()
				);
				// 2.只给有工作室的全科医生推送单子
				StudioPersonnelEntity studioPersonnel = StudioPersonnelEntity.builder()
						.deleted(FlagEnum.NO.getKey())
						.admsStateDoctor(FlagEnum.IS.getKey())
						.admsStateStudio(FlagEnum.IS.getKey())
						.build();
				for (DoctorDetailsEntity doctorDetail : doctorDetails) {
					studioPersonnel.setDoctId(doctorDetail.getId());
					List<Long> workIds = studioPersonnelSV.getSpecialistToGrabList(studioPersonnel);
					if (!workIds.isEmpty()) {
						pushBeanExtra.setPushWho(userSV.selectById(doctorDetail.getId()));
						pushBean.setExtras(pushBeanExtra);
						pushMessage(pushBean, false);
					}
				}
				return;
			} else {
				//发给专科工作室
				Long doctorDsId = orderFlow.getDoctorDsId();
				Long doctorId = orderFlow.getDoctorId();
				if (doctorDsId != null) {
					// 如果工作室关闭不推送
					DoctorStudioEntity doctorStudio = doctorStudioSV.selectById(doctorDsId);
					if (DoctorStudioStatusEnum.SHUT_DOWN.getKey().equals(doctorStudio.getState())) {
						return;
					}
				}
				// 如果有指定医生，直接给指定医生发送推送
				if (doctorId != null) {
					PushBeanExtraVo pushBeanExtraVo2 = new PushBeanExtraVo();
					BeanUtils.copyProperties(pushBeanExtra, pushBeanExtraVo2);
					pushBeanExtraVo2.setPushWho(userSV.selectById(doctorId));
					InquiryOrderIoTypeEnum enumByCode = DictEnum.valueOfEnum(InquiryOrderIoTypeEnum.class, inquiryOrder.getIoType());
					switch (enumByCode) {
						case BY_CONSULTING:
							pushBeanExtraVo2.setMsgTypeSub("02");
							break;
						case VIDEO_CONSULTATION:
							pushBeanExtraVo2.setMsgTypeSub("03");
							break;
						case TELEPHONE_COUNSELING:
							pushBeanExtraVo2.setMsgTypeSub("01");
							break;
					}
					pushBean.setExtras(pushBeanExtraVo2);
					String msg = JPushUtil.getMessageByPushBean(pushBean);
					pushBean.setAlert(msg);
					pushMessage(pushBean, false);
					return;
				}
				List<StudioPersonnelEntity> studioPersonnels = studioPersonnelSV.selectList(
						StudioPersonnelEntity.builder()
								.dsId(doctorDsId)
								.deleted(FlagEnum.NO.getKey())
								.admsStateDoctor(FlagEnum.IS.getKey())
								.admsStateStudio(FlagEnum.IS.getKey())
								.build()
				);
				for (StudioPersonnelEntity studioPersonnel : studioPersonnels) {
					pushBeanExtra.setPushWho(userSV.selectById(studioPersonnel.getDoctId()));
					pushBean.setExtras(pushBeanExtra);
					pushMessage(pushBean, false);
				}
				return;
			}
		});
	}
}
